const request = require("request");
const req = {
    get : (url, options) => {
        request({
            url: url,
            method: 'get',
            qs: options.data
        },(error , res, body) => {
            try {
                let result = JSON.parse(body) || {};
                if (!error && res.statusCode == 200) {
                    options.success ? options.success(result, res) : undefined;
                } else {
                    options.failure ? options.failure(result, res) : undefined;
                }
                options.callback ? options.callback(result, res) : undefined;
            } catch(e) {
                options.failure ? options.failure("内部错误",res) : undefined;
            }
        });
    },
    post : (url, options) => {
        request({
            url: url,
            method: 'post',
            json: options.data
        }, (error, res, body) => {
            try{
                let result = body || {};
                if(!error && res.statusCode == 200){
                    options.success ? options.success(result,res) : undefined;
                }else {
                    options.failure ? options.failure(error) : undefined;
                }
                options.callback ? options.callback(result,res) : undefined;
            }catch(e){
                options.failure ? options.failure("内部错误",res) : undefined;
            }
        });

    },
    success : (result, res) => {
        res.json({
            status: true,
            data: result
        });
    },
    failure : (error, res) => {
        res.json({
           status : false,
            error : error
        });
    }
};
module.exports = req;
